<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;text-align: center">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.keyword" placeholder="Keyword" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">用户账号注册</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="50">
      </el-table-column>
      <el-table-column prop="username" label="姓名" width="160" sortable>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="150" sortable>
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="200" sortable>
      </el-table-column>
      <el-table-column prop="type" label="账号类型" width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.type === 1" style="color: green;">管理员</span>
          <span v-else-if="scope.row.type === 2" style="color: peru;">商家</span>
          <span v-else style="color: darkred;">用户</span>
        </template>
      </el-table-column>
      <el-table-column prop="disable" label="是否可用" width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.disable == 1" style="color: green;">可用</span>
          <span v-else style="color: red;">不可用</span>
        </template>
      </el-table-column>
      <el-table-column prop="balance" label="用户余额" width="100" sortable>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template scope="scope">
          <el-button type="danger" v-if="scope.row.type === 1" size="small"
                     @click="handleManagerEdit(scope.$index, scope.row)">管理员修改
          </el-button>
          <el-button type="danger" v-if="scope.row.type === 2" size="small"
                     @click="handleManagerEdit(scope.$index, scope.row)">商家修改
          </el-button>
          <el-button type="danger" v-if="scope.row.type == null" size="small"
                     @click="handleEdit(scope.$index, scope.row)">用户修改
          </el-button>
          <el-button type="success" v-if="scope.row.type == null" size="small"
                     @click="handleRecharge(scope.$index, scope.row)">充值
          </el-button>
          <el-button type="success" v-if="scope.row.type != null" size="small"
                     @click="handleRole(scope.$index, scope.row)">设置角色
          </el-button>
          <el-button type="danger" v-if="scope.row.type == null" size="small"
                     @click="handleDel(scope.$index, scope.row)">用户删除
          </el-button>
          <el-button type="danger" v-if="scope.row.type != null && scope.row.type != 1" size="small"
                     @click="handleManagerDel(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
<!--      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>-->
      <!--      @size-change 当每页显示条数的值发生改变时会触发-->
      <!--      @current-change 当 当前页的值发生改变时会触发-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="query.pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
          :current-page="query.currentPage"
          style="float: right">
      </el-pagination>
    </el-col>

    <!--用户 新增/修改 界面-->
    <el-dialog title="用户 新增/修改 界面" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="addForm">
        <el-form-item label="姓名" prop="username" >
          <el-input v-model="saveForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="text" v-model="saveForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input type="text" v-model="saveForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="text" v-model="saveForm.password"></el-input>
        </el-form-item>
        <el-form-item label="余额" prop="balance">
          <el-input type="text" v-model="saveForm.balance"></el-input>
        </el-form-item>
<!--        <el-form-item label="头像">-->
<!--          <el-input type="textarea" v-model="saveForm.headImg"></el-input>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--商家/管理员 新增/修改 界面-->
    <el-dialog title="商家/管理员 新增/修改 界面" :visible.sync="saveManagerVisible" :close-on-click-modal="false">
      <el-form :model="saveManager" label-width="80px" :rules="saveFormRules" ref="addForm">
        <el-form-item label="姓名">
          <el-input v-model="saveForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机">
          <el-input type="text" v-model="saveForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="text" v-model="saveForm.password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveManagerVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveManagerSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

    <!-- 设置权限 编辑页面 -->
    <el-dialog title="设置角色" :visible.sync="setRoleVisible" :close-on-click-modal="false">
      <el-form :model="EmployeeRole" label-width="80px" ref="saveForm">
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
        </el-checkbox>
        <div class="checkbox-table" v-for="(p,indexkey) in Roles" :key="p.id">
          <!--
          label:就是当前复选框的值
          -->
          <el-checkbox class="check1" style="font-weight: 600;margin-bottom: 15px "
                       v-model='EmployeeRole.roleId' :label="p.id"
                       @change='handleCheck(1,indexkey)'>
            {{ p.name }}
          </el-checkbox>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="setRoleVisible = false">Cancel</el-button>
        <el-button type="primary" @click.native="saveEmployeeRole" :loading="addLoading">Submit</el-button>
      </div>
    </el-dialog>

    <!-- 充值弹框 -->
    <el-dialog title="充值" :visible.sync="rechargeVisible" :close-on-click-modal="false">
      <el-form :model="rechargeDTO" label-width="80px" ref="addForm">
        <el-form-item label="充值金额">
          <el-input v-model="rechargeDTO.balance" placeholder="请输入充值金额"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="rechargeVisible = false">取消</el-button>
        <el-button type="primary" @click.native="balanceRecharge" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>


export default {
  data() {
    return {
      pageInfo: {
        rows: [],
        total: 0
      },
      query: {
        currentPage: 1,
        pageSize: 20,
        keyword: ""
      },

      listLoading: false,
      sels: [],//列表选中列

      saveFormVisible: false, // 用户编辑界面是否显示
      saveManagerVisible: false, // 管理员商家编辑界面是否显示

      addLoading: false,
      saveFormRules: {
        username: [
          {required: true, message: '请输入用户字', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入手机号码', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ]
      },

      // 用户编辑界面数据
      saveForm: {
        id: null,
        username: '',
        email: '',
        phone: '',
        password: '',
        balance:''

      },

      // 管理员商家编辑界面数据
      saveManager: {
        id: null,
        username: '',
        email: '',
        phone: '',
        password: '',
        headImg: ''
      },

      departments: [],

      //设置角色相关data
      setRoleVisible: false,  //弹框控制
      EmployeeRole: {
        managerId: null,
        roleId: []
      },
      isIndeterminate: false,   //多选的状态
      checkAll: false,
      Roles: [],          //用来显示数据
      allRoleIds: [],     //用来装所有角色的id

      rechargeDTO: {
        id: null,
        balance: null
      },
      rechargeVisible: false,

    }
  },
  methods: {

    //全选按钮
    handleCheckAllChange(val) {
      this.EmployeeRole.roleId = val ? this.allRoleIds : []
      this.isIndeterminate = false;
    },

    //角色弹框设置
    handleRole: function (index, row) {
      this.setRoleVisible = true;
      this.getRoles();
      this.getAllRoleIds();
      this.EmployeeRole.managerId = row.id;
      //传当前对象的id做数据回显
      this.getRoleByRoleId(row.id);
    },

    // 充值弹框设置
    handleRecharge: function (index, row) {
      this.rechargeVisible = true;
      this.rechargeDTO.id = row.id;
    },

    //获取所有角色
    getRoles() {
      this.$http.get("/role")
          .then(result => {
            result = result.data;
            if (result.success) {
              this.Roles = result.resultObj
            }
          }).catch(result => {
        this.$message({message: '网络错误', type: 'error'});
      })
    },

    //获取所有角色的id
    getAllRoleIds() {
      this.$http.get("/role/ids")
          .then(result => {
            result = result.data;
            if (result.success) {
              this.allRoleIds = result.resultObj;
            }
          }).catch(result => {
        this.$message({message: '网络错误', type: 'error'});
      })
    },

    //根据managerId做回显
    getRoleByRoleId(managerId) {
      this.$http.get("/manager/role/" + managerId)
          .then(result => {
            result = result.data;
            if (result.success) {
              this.EmployeeRole.roleId = result.resultObj;
              // 获取已选中的长度
              let checkedLength = this.EmployeeRole.roleId.length;
              // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
              this.checkAll = checkedLength === this.allRoleIds.length;
              // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
              this.isIndeterminate = checkedLength > 0 && checkedLength < this.allRoleIds.length;
            }
          }).catch(result => {
        this.$message({message: '网络错误', type: 'error'});
      })
    },

    // 设置角色保存
    saveEmployeeRole() {
      this.$confirm('确认提交菜单选择吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.post("/manager/role", this.EmployeeRole)
            .then(result => {
              result = result.data;
              if (result.success) {
                this.setRoleVisible = false;
                this.$message({message: result.message, type: 'success'});
              } else {
                this.$message({message: result.message, type: 'error'});
              }
            }).catch(result => {
          this.$message({message: '网络错误', type: 'error'});
        })
      })
    },

    // 处理选择事件
    handleCheck() {
      // 获取已选中的长度
      let checkedLength = this.EmployeeRole.roleId.length;
      // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
      this.checkAll = checkedLength === this.allRoleIds.length;
      // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
      this.isIndeterminate = checkedLength > 0 && checkedLength < this.allRoleIds.length;
    },

    // 搜索
    search() {
      // 设置query.currengPage为1,当进行搜索时,从第一页开始重新进行搜索
      this.query.currentPage = 1;
      //调用查询
      this.getManager();
    },

    handleSizeChange(val) {
      this.query.pageSize = val;
      this.query.currentPage = 1;
      //查询结果
      this.getManager();
    },

    handleCurrentChange(val) {
      // val为当前页，赋值后重新进行查询
      this.query.currentPage = val;
      // 调用查询方法
      this.getManager();
    },

    // 获取用户列表
    getManager() {
      this.$http.post("/manager", this.query)
          .then(result => {
            result = result.data;
            if (result.success) {
              this.pageInfo = result.resultObj;
              console.log("222222222222")
              console.log(this.pageInfo);
            } else {
              this.$message({message: result.message, type: 'error'});
            }
          })
          .catch(result => {

          })
    },

    // 用户删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/user/" + row.id)
            .then(result => {
              result = result.data;
              this.listLoading = false;
              if (result.success) {
                this.$message({message: '删除成功', type: 'success'});
                //删除成功后回到第一页
                this.query.currentPage = 1;
                // 删除成功,要重新刷新该页面，调用方法查询
                this.getManager();
              } else {
                this.$message({message: result.message, type: 'error'});
              }
            })
            .catch(result => {
              this.$message({message: '很抱歉，网络有误', type: 'error'});
            })
      }).catch(() => {
        this.$message({message: '已取消删除', type: 'info'});
      });
    },

    // 管理员或商家删除
    handleManagerDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/manager/" + row.id)
            .then(result => {
              result = result.data;
              this.listLoading = false;
              if (result.success) {
                this.$message({message: '删除成功', type: 'success'});
                //删除成功后回到第一页
                this.query.currentPage = 1;
                // 删除成功,要重新刷新该页面，调用方法查询
                this.getManager();
              } else {
                this.$message({message: result.message, type: 'error'});
              }
            })
            .catch(result => {
              this.$message({message: '很抱歉，网络有误', type: 'error'});
            })
      }).catch(() => {
        this.$message({message: '已取消删除', type: 'info'});
      });
    },

    // 管理员商家显示修改界面(回显数据)
    handleManagerEdit: function (index, row) {
      this.saveManagerVisible = true;
      this.saveForm = Object.assign({}, row);
    },

    // 用户显示修改界面(回显数据)
    handleEdit: function (index, row) {
      this.saveFormVisible = true;
      this.saveForm = Object.assign({}, row);
    },

    // 显示新增界面
    handleAdd: function () {
      this.saveFormVisible = true;
      this.saveForm = {
        id: null,
        username: '',
        email: '',
        phone: '',
        password: ''
      };
    },

    // 用户提交
    saveSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            var para = this.saveForm;
            this.$http.put("/user", para)
                .then(result => {
                  result = result.data;
                  if (result.success) {
                    //从第一页开始展示
                    this.query.currentPage = 1;
                    this.getManager();
                    //关闭加载框
                    this.addLoading = false;
                    //关闭弹框
                    this.saveFormVisible = false;
                    this.$message({message: '保存成功', type: 'success'});
                  }else {
                    //关闭加载框
                    this.addLoading = false;
                    this.$message({message:result.message,type:'warning'})
                  }
                }).catch(result => {
              this.$message({message:"网络错误，稍后再试",type:'warning'});
            })
          });
        }
      });
    },

    // 管理员商家提交
    saveManagerSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            var para = this.saveForm;
            this.$http.put("/manager", para)
                .then(result => {
                  result = result.data;
                  if (result.success) {
                    //从第一页开始展示
                    this.query.currentPage = 1;
                    this.getManager();
                    //关闭加载框
                    this.addLoading = false;
                    //关闭弹框
                    this.saveManagerVisible = false;
                    this.$message({message: '保存成功', type: 'success'});
                  }
                }).catch(result => {
              this.$message({message: '网络错误', type: 'error'});
            })
          });
        }
      });
    },

    selsChange: function (sels) {
      this.sels = sels;
    },

    // 余额充值提交
    balanceRecharge() {
      this.$confirm('确认提交吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.post("/user/recharge", this.rechargeDTO)
            .then(result => {
              result = result.data;
              if (result.success) {
                this.rechargeVisible = false;
                this.getManager();
                this.$message({message: result.message, type: 'success'});
              } else {
                this.$message({message: result.message, type: 'error'});
              }
            }).catch(result => {
          this.$message({message: '网络错误', type: 'error'});
        })
      })
    },

    // 批量删除员工
    batchRemove: function () {
      //遍历选中的sels数组的id值给ids
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        // 调用批量删除接口
        this.$http.patch("/manager", ids)
            .then(result => {
              result = result.data;
              this.listLoading = false;
              if (result.success) {
                this.$message({message: '批量删除成功!', type: 'success'});
                //删除后回到第一页
                this.query.currentPage = 1;
                //调用查询
                this.getManager();
              } else {
                this.$message({message: result.message, type: 'error'});
              }
            })
      }).catch(() => {
        this.$message({message: "网络错误", type: 'error'});
      });
    }
  },

  mounted() {
    // 钩子函数，页面加载后，调用此方法，加载部门
    this.getManager();
  }
}

</script>

<style scoped>

</style>
